import { defineStore } from "pinia"
import { reportmanagement } from '@/api'

export const useReportManagementStore = defineStore('reportManagement', {
    state: () => ({
        taskLineData: [], // 折线图数据
        taskStatusData: [], // 柱状图数据 [进行中, 已完成, 未完成]
        loading: false,
        error: null
    }),

    actions: {
        async fetchReportData(params) {
            this.loading = true
            this.error = null

            try {
                const res = await reportmanagement(params)
                console.log('接口返回数据:', res)

                if (res.data?.data && Array.isArray(res.data.data)) {
                    const dateMap = new Map()

                    // 如果有时间范围，创建日期范围内的映射
                    if (params.createTime && params.endTime) {
                        const startDate = new Date(Number(params.createTime))
                        const endDate = new Date(Number(params.endTime))
                        
                        // 填充日期范围内的所有日期
                        for (let d = new Date(startDate); d <= endDate; d.setDate(d.getDate() + 1)) {
                            const dateStr = `${d.getMonth() + 1}/${d.getDate()}`
                            dateMap.set(dateStr, {
                                date: dateStr,
                                fullDate: d.toLocaleDateString(),
                                value: 0
                            })
                        }
                    }

                    // 处理实际数据
                    res.data.data.forEach(item => {
                        const d = new Date(item.createTime)
                        const dateStr = `${d.getMonth() + 1}/${d.getDate()}`
                        const completedTasks = item.reportWorkStatusCountModels.find(
                            model => model.workStatusId === 1
                        )
                        
                        // 如果日期不在 Map 中，添加新的日期
                        if (!dateMap.has(dateStr)) {
                            dateMap.set(dateStr, {
                                date: dateStr,
                                fullDate: d.toLocaleDateString(),
                                value: 0
                            })
                        }
                        
                        // 更新已完成任务数量
                        if (completedTasks) {
                            const existingData = dateMap.get(dateStr)
                            dateMap.set(dateStr, {
                                ...existingData,
                                value: completedTasks.count
                            })
                        }
                    })

                    // 转换为数组并按日期排序
                    this.taskLineData = Array.from(dateMap.values())
                        .sort((a, b) => new Date(a.fullDate) - new Date(b.fullDate))

                    console.log('处理后的折线图数据:', this.taskLineData)

                    // 处理柱状图数据保持不变
                    const totalInProgress = res.data.data.reduce((sum, item) => {
                        const statusData = item.reportWorkStatusCountModels.find(
                            model => model.workStatusId === 0
                        )
                        return sum + (statusData?.count || 0)
                    }, 0)

                    const totalCompleted = res.data.data.reduce((sum, item) => {
                        const statusData = item.reportWorkStatusCountModels.find(
                            model => model.workStatusId === 1
                        )
                        return sum + (statusData?.count || 0)
                    }, 0)

                    const totalExpired = res.data.data.reduce((sum, item) => {
                        const statusData = item.reportWorkStatusCountModels.find(
                            model => model.workStatusId === 2
                        )
                        return sum + (statusData?.count || 0)
                    }, 0)

                    this.taskStatusData = [totalInProgress, totalCompleted, totalExpired]
                }
            } catch (error) {
                console.error('请求失败:', error)
                this.error = error.message || '获取报表数据失败'
            } finally {
                this.loading = false
            }
        }
    }
})